package com.example.controller;

import com.example.common.Result;
import com.example.interceptor.SSOSessionData;
import com.example.interceptor.UserSessionHolder;
import com.example.model.bo.LoginInfo;
import com.example.model.bo.TracePathDto;
import com.example.service.IpfsService;
import com.example.service.LoginService;
import com.example.service.TracePathService;
import jnr.a64asm.Register;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@CrossOrigin
public class TracePathController {

    @Autowired
    private TracePathService tracePathService;

    @Autowired
    private LoginService loginService;

    /**
     * 溯源文件的传输路径
     * @param tracePathDto
     * @return
     * @throws Exception
     */
    @PostMapping("/tracePath")
    public Result tracePath(@RequestBody TracePathDto tracePathDto) throws Exception {
        log.info("路径溯源：{}", tracePathDto);
        //调用service层获取路径
        List<String> path = tracePathService.tracePath(tracePathDto);
        //反转列表
        Collections.reverse(path);
        return Result.success(path);
    }


    /**
     * 文件进行溯源传输
     * @param file
     * @param receiverUserName
     * @return
     * @throws Exception
     */
    @PostMapping("/trace")
    public Result DataTraceability(@RequestParam("file") MultipartFile file,
                                   @RequestParam(value = "receiverUserName", required = false, defaultValue = "null")String receiverUserName)throws Exception {
//        log.info("shdashdjashdasjhdasjhdasjdhas");


//        SSOSessionData currentUser = UserSessionHolder.getCurrentUser();
//        String username = currentUser.getUsername();
//
////        System.out.println("realm:"+realm);
//        LoginInfo dto = new LoginInfo(username, "1231", true);
//        Map<String, String> register_resp = loginService.register(dto);
////        if (Objects.equals(register_resp.get("state"), "success")){
//////            return Result.success(register_resp.get("address"));
//////        }

        return tracePathService.DataTraceability(file, receiverUserName);
    }


    /**
     * 下载溯源上传的文件
     */
    @Autowired
    private IpfsService ipfsService;
    @RequestMapping("/gettracefile")
    public ResponseEntity<FileSystemResource> downloadBigIpfs(String cid, String filename) throws Exception {
        String commonPath = "/opt/demo/back/assets/";
//        String commonPath = "src/main/java/com/example/assets";
        ipfsService.downFromIpfs(cid, commonPath+filename);
        File file = new File(commonPath+filename);
        // 检查文件是否存在
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }
        // 如果文件不是可读的，也返回404或者其他错误
        if (!file.canRead()) {
            return ResponseEntity.status(403).build(); // 403 Forbidden
        }
        // 设置Content-Type为适当的MIME类型（例如text/plain, application/pdf等）
        // 如果不确定，可以使用application/octet-stream
        String contentType = "application/octet-stream"; // 二进制文件，通常用于下载时不确定MIME类型
        // 创建FileSystemResource实例
        FileSystemResource resource = new FileSystemResource(file);
        // 告诉浏览器这是一个附件，并提供文件名
        String encodedFileName = URLEncoder.encode(filename, "UTF-8");
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"")
                .body(resource);
    }


}
